package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.EmployeeQueryObject;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.service.IEmployeeService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class EmployeeServiceImpl implements IEmployeeService{
    @Autowired
    private EmployeeMapper employeeMapper;

    public int deleteByPrimaryKey(Long id) {
        //删除关系
        employeeMapper.deleteRelation(id);
        return employeeMapper.deleteByPrimaryKey(id);
    }

    public int insert(Employee record) {
        //先保存
        int emp = employeeMapper.insert(record);
        List<Role> roles = record.getRoles();
        if(roles != null){
            for (Role role : roles) {
                //维护中间关系
                employeeMapper.insertRelation(record.getId(), role.getId());
            }
        }
        return  emp;
    }

    public Employee selectByPrimaryKey(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    public int updateByPrimaryKey(Employee record) {
        //先更新
        int emp = employeeMapper.updateByPrimaryKey(record);
        //删除关系再添加
        employeeMapper.deleteRelation(record.getId());
        List<Role> roles = record.getRoles();
        if(roles != null){
            for (Role role : roles) {
                //维护中间关系
                employeeMapper.insertRelation(record.getId(), role.getId());
            }

        }
        return emp;
    }
    //检查用户是否存在
    public Employee checkName(String username) {
        return employeeMapper.checkName(username);
    }

    //分页
    public PageResult query(EmployeeQueryObject qo){
        //查总数
        int total = employeeMapper.queryForCount(qo);
         if(total==0){
             return new PageResult();
         }
         //查每页数据
        List<Employee> rows = employeeMapper.queryForList(qo);

        return new PageResult(rows,total);
    }

    public void changeState(Long id) {
        employeeMapper.changeState(id) ;
    }

    //修改密码
    public int updatePasswordById(String password) {
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        return employeeMapper.updatePasswordById(employee.getId(),password);
    }

    @Override
    public Employee selectUsername(String uname) {
        return employeeMapper.selectUsername(uname);
    }


}
